import {
  Controller,
  Get,
  Post,
  Body,
  Req,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { AnalyticsService } from './analytics.service';
import { CreateAnalyticsDto } from './dto/analytics.dto';
import { ApiExcludeEndpoint, ApiTags } from '@nestjs/swagger';
import { AdminAnalyticsSummaryResDto } from './dto/admin-analytics.dto';
import { UserService } from '../user/user.service';
import { PunchService } from '../punch/punch.service';

@ApiTags('小程序/事件')
@Controller('app/analytics')
export class AnalyticsController {
  constructor(private readonly analyticsService: AnalyticsService) {}

  /**
   * 创建事件
   */
  @ApiExcludeEndpoint()
  @Post()
  async create(@Req() req: Request, @Body() data: CreateAnalyticsDto) {
    if (!req.user?.userId) {
      throw new HttpException('用户未登录', HttpStatus.UNAUTHORIZED);
    }
    await this.analyticsService.create(req.user?.userId, data.eventType);
  }
}

@ApiTags('后台/事件')
@Controller('admin/analytics')
export class AdminAnalyticsController {
  constructor(
    private readonly analyticsService: AnalyticsService,
    private readonly userService: UserService,
    private readonly punchService: PunchService,
  ) {}

  /**
   * 事件总览
   */
  @Get()
  async analyticsSummary(): Promise<AdminAnalyticsSummaryResDto> {
    const analytics = await this.analyticsService.summary();
    const userCount = await this.userService.count();
    const punchTodayList = await this.punchService.findRangePunchData();

    return {
      userCount,
      analytics,
      punchTodayList,
    };
  }
}
